/* 
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.avdheshyadav.p4j.sample.server.guice;


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import com.avdheshyadav.p4j.jdbc.PersistenceConfig;
import com.avdheshyadav.p4j.jdbc.dbms.DataProviderFactoryImpl;
import com.avdheshyadav.p4j.jdbc.service.DataProviderFactory;
import com.avdheshyadav.p4j.sample.server.dao.LibraryDataRepository;
import com.avdheshyadav.p4j.sample.server.handler.FetchBooksHandler;
import com.avdheshyadav.p4j.sample.shared.rpc.FetchBooksAction;
import com.google.inject.Singleton;
import com.google.inject.name.Names;

import net.customware.gwt.dispatch.server.guice.ActionHandlerModule;


public class GuiceServerModule extends ActionHandlerModule 
{
	String persistenceFileName = "persistence.properties";
	
    private String rootPath;
    
    public GuiceServerModule(String rootPath)
    {
    	this.rootPath = rootPath;
    }

    @Override
    protected void configureHandlers()
    {
    	bindHandler(FetchBooksAction.class, FetchBooksHandler.class);    	
    	
    	Properties properties = new Properties();
    	try {
    		properties = loadPropertiesFile();
			Names.bindProperties(binder(), properties);
		} catch (Exception e) {
			 throw new RuntimeException("Unable to Load persistence Properties file," + e);
		}
		//
    	// This properties can be injected anywhere
    	bind(Properties.class).toInstance(properties);
    	// This allows us to inject persistence anywhere we want
    	PersistenceConfig config = new PersistenceConfig(properties);
    	bind(PersistenceConfig.class).toInstance(config);
    	bind(DataProviderFactory.class).toInstance((new DataProviderFactoryImpl(config)));
    	bind(LibraryDataRepository.class).toProvider(LibraryDataRepoProvider.class).in(Singleton.class);
    }
    
    
    /**
     * 
     * @param context Properties
     * 
     * @return ServletContext
     * 
     * @throws Exception 
     */
    private Properties loadPropertiesFile() throws Exception
    {
    	String propertiesFile = rootPath + "WEB-INF/" + persistenceFileName;
    	InputStream inputStream = new FileInputStream(propertiesFile);
    	Properties properties = new Properties();
		properties.load(inputStream);
		inputStream.close();
		return properties;
    }
}
